from html_00_common_header import generate_common_header
from html_01_common_footer import generate_common_footer


def handle_question_path(self, parsed_path):
    try:
        question_id = int(parsed_path.path.split('/')[-1])
        if 0 > question_id or question_id >= len(self.questions):
            self.send_error(404, '', '题目不存在')
            return
    except ValueError:
        self.send_error(400, '', '无效的题目ID' + parsed_path.path)
        return

    try:
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        self.wfile.write(generate_question_html(self.questions[question_id]).encode('utf-8'))
    except ValueError as e:
        self.send_error(400, '', str(e))
        return


def generate_question_html(question):
    """根据题型生成完整的题目 HTML 内容"""

    icon = ''
    if question['题目类型'] == "判断题":
        body = generate_judgment_html(question)
        icon = '✓✗'
    elif question['题目类型'] == "单选题":
        body = generate_single_choice_html(question)
        icon = "●"
    elif question['题目类型'] == "多选题":
        body = generate_multiple_choice_html(question)
        icon = "✓"
    else:
        body = "<div>未知题型</div>"  # 异常处理

    return (generate_common_header(f"{question['题号']}. {question['问题']}", icon) +
            get_style() +
            get_script() +
            body +
            generate_answer_explanation_html(question) +
            generate_next_pre_html() +
            generate_stats_info() +
            '<div id="wrong-questions"></div>' +
            generate_common_footer())


def get_script():
    return '''
<script> 
// 提取统计计算与显示的公共函数
function updateStatisticsDisplay() {
    fetch('/get_stats')
        .then(response => {
            if (!response.ok) throw new Error(`HTTP错误，状态码：${response.status}`);
            return response.json(); // 直接解析JSON（兼容性更好的标准方法）
        })
        .then(data => {
            // 兼容可能的空数据，使用默认值
            const accuracy = data.accuracy || '0.00';
            const errorRate = data.errorRate || '0.00';
            document.getElementById('accuracy-rate').textContent = accuracy + '%';
            document.getElementById('error-rate').textContent = errorRate + '%';
        })
        .catch(error => {
            console.error('加载统计数据失败:', error);
            document.getElementById('accuracy-rate').textContent = '0.00%';
            document.getElementById('error-rate').textContent = '0.00%';
        });
}

// 存储答题结果（修改为调用公共函数更新显示）
function updateStats(isCorrect) {
    const questionId = window.location.pathname.split('/').pop();
    
    // 发送到服务器保存
    fetch('/save_stats', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            questionId: questionId,
            isCorrect: isCorrect
        })
    });

    // 更新统计数据（简化fetch调用）
    fetch('/get_stats')
        .then(response => {
            if (!response.ok) throw new Error(`HTTP错误，状态码：${response.status}`);
            return response.json();
        })
        .then(data => {
            const accuracy = data.accuracy || '0.00';
            const errorRate = data.errorRate || '0.00';
            document.getElementById('accuracy-rate').textContent = accuracy + '%';
            document.getElementById('error-rate').textContent = errorRate + '%';
        })
        .catch(error => {
            console.error('更新统计数据失败:', error);
            document.getElementById('accuracy-rate').textContent = '0.00%';
            document.getElementById('error-rate').textContent = '0.00%';
        });
}

function displayWrongQuestions() {
    fetch('/get_wrong_questions')  // 改为请求服务器接口
        .then(response => {
            if (!response.ok) throw new Error(`HTTP错误，状态码：${response.status}`);
            return response.json();
        })
        .then(wrongQuestions => {
            const wrongQuestionsDiv = document.getElementById('wrong-questions');
            let html = '<h2>错误题目列表</h2>';
            // 遍历服务器返回的错误题目ID列表
            wrongQuestions.forEach(questionId => {
                html += `<a href="/question/${questionId}">题目 ${parseInt(questionId)+1}</a><br>`;
            });
            wrongQuestionsDiv.innerHTML = html;
        })
        .catch(error => {
            console.error('获取错误题目失败:', error);
            document.getElementById('wrong-questions').innerHTML = '<h2>错误题目列表加载失败</h2>';
        });
}

// 新增变量：错题列表和循环模式状态（从localStorage读取初始化值）
let wrongQuestionsList = [];
let isWrongLoopMode = localStorage.getItem('isWrongLoopMode') === 'true';  // 从存储中读取布尔值

// 页面加载时初始化按钮点击事件
window.addEventListener('load', function() {
    updateStatisticsDisplay();
    displayWrongQuestions();
    
    // 绑定错题循环按钮点击事件
    const wrongLoopBtn = document.getElementById('wrong-loop-btn');
    if (wrongLoopBtn) {
        // 初始化按钮文本（根据存储状态）
        wrongLoopBtn.textContent = isWrongLoopMode ? '关闭错题循环' : '开启错题循环';
        
        wrongLoopBtn.addEventListener('click', function() {
            isWrongLoopMode = !isWrongLoopMode;
            this.textContent = isWrongLoopMode ? '关闭错题循环' : '开启错题循环';
            // 存储状态到localStorage
            localStorage.setItem('isWrongLoopMode', isWrongLoopMode);
        });
    }
});

// 修改displayWrongQuestions存储错题列表
function displayWrongQuestions() {
    fetch('/get_wrong_questions')
        .then(response => {
            if (!response.ok) throw new Error(`HTTP错误，状态码：${response.status}`);
            return response.json();
        })
        .then(wrongQuestions => {
            const wrongQuestionsDiv = document.getElementById('wrong-questions');
            let html = '<h2>错误题目列表</h2>';
            // 存储错题ID为数字数组（用于导航）
            wrongQuestionsList = wrongQuestions.map(id => parseInt(id));
            // 生成题目链接
            wrongQuestions.forEach(questionId => {
                html += `<a href="/question/${questionId}">题目 ${parseInt(questionId)+1}</a><br>`;
            });
            wrongQuestionsDiv.innerHTML = html;
        })
        .catch(error => {
            console.error('获取错误题目失败:', error);
            document.getElementById('wrong-questions').innerHTML = '<h2>错误题目列表加载失败</h2>';
        });
}

// 修改导航逻辑支持错题循环
function navigateQuestion(direction) {
    const currentPath = window.location.pathname;
    const currentId = parseInt(currentPath.split('/').pop());
    if (isWrongLoopMode && wrongQuestionsList.length > 0) {
        // 错题循环模式：仅在错题列表中导航
        const currentIndex = wrongQuestionsList.indexOf(currentId);
        if (currentIndex === -1) {
            // 当前题目不在错题列表中，跳转到第一个错题
            window.location.href = `/question/${wrongQuestionsList[0]}`;
            return;
        }
        
        // 计算下一个索引（循环）
        let newIndex = direction === 'prev' ? currentIndex - 1 : currentIndex + 1;
        if (newIndex < 0) newIndex = wrongQuestionsList.length - 1; // 上一题循环到末尾
        if (newIndex >= wrongQuestionsList.length) newIndex = 0; // 下一题循环到开头
        
        const newId = wrongQuestionsList[newIndex];
        window.location.href = `/question/${newId}`;
    } else {
        // 普通模式：所有题目导航
        const newId = direction === 'prev' ? currentId - 1 : currentId + 1;
        window.location.href = `/question/${newId}`;
    }
}

function checkAnswer(btn, correctAnswer) {
    const userAnswer = btn.textContent.trim().split('.')[0];
    const isCorrect = userAnswer === correctAnswer;
    updateStats(isCorrect);
    const resultDiv = document.getElementById('answer-result');
    const answerInfo = document.querySelector('.answer-info');
    
    if (userAnswer === correctAnswer) {
        resultDiv.textContent = '✓ 回答正确！';
        resultDiv.className = 'answer-result correct';
    } else {
        resultDiv.textContent = '✗ 回答错误！';
        resultDiv.className = 'answer-result incorrect';
    }
    resultDiv.classList.remove('hidden');
    answerInfo.classList.remove('hidden');
    // 确保解析内容显示
    const explanation = document.querySelector('.explanation');
    if(explanation) explanation.style.display = 'block';
}

function checkMultiAnswer(btn, correctAnswer) {
    const selected = [];
    document.querySelectorAll('.options input[type="checkbox"]:checked').forEach(checkbox => {
        selected.push(checkbox.value);
    });
    
    if(selected.length === 0) {
        alert('请至少选择一个选项');
        return;
    }
    
    const userAnswer = selected.sort().join('');
    const sortedCorrect = correctAnswer.split('').sort().join('');
    const isCorrect = userAnswer === sortedCorrect;
    updateStats(isCorrect);
    const resultDiv = document.getElementById('answer-result');
    const answerInfo = document.querySelector('.answer-info');
    
    if (userAnswer === sortedCorrect) {
        resultDiv.textContent = '✓ 回答正确！';
        resultDiv.className = 'answer-result correct';
    } else {
        resultDiv.textContent = '✗ 回答错误！';
        resultDiv.className = 'answer-result incorrect';
    }
    resultDiv.classList.remove('hidden');
    answerInfo.classList.remove('hidden');
    // 确保解析内容显示
    const explanation = document.querySelector('.explanation');
    if(explanation) explanation.style.display = 'block';
}
</script>
'''


def generate_answer_explanation_html(question):
    """生成公共的解析信息和交互脚本部分"""
    return f"""
<div class="answer-info hidden">
    <div>正确答案: {question['答案']}</div>
    <div class="explanation">解析: {question['解析']}</div>
</div>
"""


def generate_judgment_html(question):
    """生成判断题的HTML内容"""
    return f"""
<div class="question judgment-question">
    <div class="question-number">{question['题号']}.</div>
    <div class="question-text">{question['问题']}</div>
    <div class="options">
        <button class="judgment-btn" onclick="checkAnswer(this, '{question['答案']}')">正确</button>
        <button class="judgment-btn" onclick="checkAnswer(this, '{question['答案']}')">错误</button>
    </div>
    <div class="answer-result hidden" id="answer-result"></div>
</div>
"""


def generate_single_choice_html(question):
    """生成单选题的HTML内容"""
    options_html = "".join([
        f'<button class="option-btn" onclick="checkAnswer(this, \'{question["答案"]}\')">{opt["key"]}. {opt["text"]}</button>'
        for opt in question.get('选项', [])
    ])
    return f"""
<div class="question single-question">
    <div class="question-number">{question['题号']}.</div>
    <div class="question-text">{question['问题']}</div>
    <div class="options">{options_html}</div>
    <div class="answer-result hidden" id="answer-result"></div>
</div>
"""


def generate_multiple_choice_html(question):
    """生成多选题的HTML内容"""
    options_html = "".join([
        f'<div class="option" style="display:flex; align-items:center;">'
        f'<input type="checkbox" id="opt-{opt["key"]}" value="{opt["key"]}">'
        f'<label for="opt-{opt["key"]}" style="flex:1; padding:8px; cursor:pointer;">{opt["key"]}. {opt["text"]}</label>'
        f'</div>'
        for opt in question.get('选项', [])
    ])
    return f"""
<div class="question multiple-question">
    <div class="question-number">{question['题号']}.</div>
    <div class="question-text">{question['问题']}</div>
    <div class="options">{options_html}</div>
    <button class="submit-btn" onclick="checkMultiAnswer(this, '{question["答案"]}')">提交答案</button>
    <div class="answer-result hidden" id="answer-result"></div>
</div>
"""


def get_style():
    return '''
<style>
.explanation {
    display: none;
    margin-top: 20px;
    padding: 10px;
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 5px;
}
.question {
    font-size: 1.2em;
    margin-bottom: 20px;
}
.answer {
    cursor: pointer;
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}
.answer:hover {
    background-color: #f0f0f0;
}
.hidden {
    display: none;
}
.answer-result {
    margin: 15px 0;
    padding: 10px;
    border-radius: 5px;
    font-weight: bold;
}
.correct {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}
.incorrect {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
.judgment-btn, .option-btn {
    margin: 5px;
    padding: 8px 15px;
    background-color: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
}
.judgment-btn:hover, .option-btn:hover {
    background-color: #e2e6ea;
}
.options {
    margin: 15px 0;
}
.option {
    margin: 8px 0;
    padding: 8px;
    background: #f8f9fa;
    border-radius: 4px;
    display: flex;
}
.submit-btn {
    margin-top: 15px;
    padding: 10px 20px;
    background: #66ccff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
.submit-btn:hover {
    background: #4db8ff;
}
</style>
'''


def generate_next_pre_html():
    return '''
<div class="question-navigation">
    <button class="nav-btn" onclick="navigateQuestion('prev')">❮ 上一题</button>
    <button class="nav-btn" onclick="navigateQuestion('next')">下一题 ❯</button>
    <button class="nav-btn" id="wrong-loop-btn">开启错题循环</button>
    <button class="nav-btn" onclick="window.location.href = '/'">返回主页</button>
</div>
<style>
    .question-navigation {
        display: flex;
        margin-top: 20px;
    }
    .nav-btn {
        margin-right: 15px;
        padding: 8px 16px;
        background-color: #66ccff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .nav-btn:hover {
        background-color: #4db8ff;
    }
</style>
<script>
// 添加键盘事件监听
document.addEventListener('keydown', function(event) {
    const arrowKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'];
    if (arrowKeys.includes(event.key)) {
        event.preventDefault();
        if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
            navigateQuestion('prev');
        } else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
            navigateQuestion('next');
        }
    } else if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        if (event.shiftKey) {
            navigateQuestion('prev');
        } else {
            navigateQuestion('next');
        }
    }
});
</script>
'''


def generate_stats_info():
    return '''
<style>
.stats {
    margin-top: 20px;
    padding: 10px;
    background-color: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 4px;
}
</style>
<div class="stats" id="stats">
    <div>当前正确率: <span id="accuracy-rate">0%</span></div>
    <div>当前错误率: <span id="error-rate">0%</span></div>
</div>
'''